package com.molichuxing.gateway.api.services.impl;

import com.molichuxing.framework.exception.BizException;
import com.molichuxing.gateway.api.services.AlipayApiService;
import com.molichuxing.gateway.bff.order.services.OrderBffService;
import com.molichuxing.gateway.bff.payment.services.AlipayBffService;
import com.molichuxing.services.business.dto.response.NotifyBizDto;
import com.molichuxing.services.property.PaymentResultEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Api(tags = "支付宝支付回调api")
@RestController
@RequestMapping(value = "/alipay")
public class AlipayApiServiceImpl extends RootApiService implements AlipayApiService {
	private static final Logger logger = LoggerFactory.getLogger(AlipayApiServiceImpl.class);

	@Resource
	private AlipayBffService alipayBffService;

	@Resource
	private OrderBffService orderBffService;

	@Override
	@ApiOperation(value = "支付宝支付结果通知")
	@PostMapping(value = "/notify/pay")
	public String notifyPay(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 从支付宝回调的request域中取值获取支付宝返回的参数集合
			Map<String, String[]> aliParams = request.getParameterMap();
			logger.info("[notifyPay]支付宝支付结果: ({})", aliParams);
			if (aliParams == null || aliParams.isEmpty()) {
				return "fail";
			}
			NotifyBizDto notifyBizDto = alipayBffService.modifyNotifyPay(aliParams);
			if (PaymentResultEnum.SUCCESS.equals(notifyBizDto.getPayResult())) {
				// 成功，修改订单信息(异步)
				orderBffService.modifyOrderPay(notifyBizDto);
			}
			return "success";
		} catch (BizException e) {
			if (e.getExceptionCode() != null && e.getExceptionCode() == 110) {
				return "success";
			} else {
				logger.error("支付宝支付结果通知异常:", e);
				return "fail";
			}
		} catch (Exception e) {
			logger.error("支付宝支付结果通知异常:", e);
			return "fail";
		}
	}
}
